package com.williamoneil.charts.server;

import java.util.Date;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.williamoneil.charts.client.ChartService;
import com.williamoneil.charts.server.controller.ChartController;
import com.williamoneil.charts.server.controller.SymbolSearchController;
import com.williamoneil.charts.server.util.ResponseUtil;
import com.williamoneil.charts.shared.ChartData;
import com.williamoneil.charts.shared.ChartResponse;
import com.williamoneil.charts.shared.PeriodicityType;
import com.williamoneil.charts.shared.SymbolData;
import com.williamoneil.charts.shared.SymbolResponse;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class ChartServiceImpl extends RemoteServiceServlet implements ChartService {

	static {
		if(false) {
			System.setProperty("http.proxyHost", "proxy.dai.netdai");
			System.setProperty("https.proxyHost", "proxy.dai.netdai");
		
			System.setProperty("http.proxyPort", "80");
			System.setProperty("https.proxyPort", "80");
		
			System.setProperty("proxySet", "true");
		}
	}
	
	@Override
	public SymbolResponse getSymbol(String symbol) {
		final SymbolResponse response = new SymbolResponse();
		
		try {
			final SymbolData data = SymbolSearchController.getInstance(super.getServletContext()).getSymbolData(symbol);
			response.setSymbolData(data);
			
			response.setHeader(ResponseUtil.getSuccessHeader());
		}catch(Exception ex) {
			response.setHeader(ResponseUtil.getErrorHeader(ex));
		}
		
		return response;
	}
	
	@Override
	public ChartResponse getChartData(String symbol, PeriodicityType periodicity, int numNodes, Date endDt) {
		final ChartResponse response = new ChartResponse();
		
		try {
			final ChartData data = ChartController.getInstance().getChartData(symbol, periodicity, numNodes, endDt);
			response.setChartData(data);
			
			// set periodicity
			data.setPeriodicity(periodicity);
			/*
			// get symbol-data
			final SymbolData symbolData = SymbolSearchController.getInstance(super.getServletContext()).getSymbolData(symbol);
			if(symbolData == null) {
				throw new Exception("No symbol found for :" + symbol);
			}
			response.getChartData().setSymbol(symbolData);
			*/
			response.setHeader(ResponseUtil.getSuccessHeader());
		}catch(Exception ex) {
			ex.printStackTrace();
			response.setHeader(ResponseUtil.getErrorHeader(ex));
		}
		
		return response;
	}
}
